package com.jfreer.mybatis.expand.xmlmapper.elements;

import com.jfreer.mybatis.expand.IntrospectedTableMyBatis3Freework;
import org.mybatis.generator.api.IntrospectedColumn;
import org.mybatis.generator.api.dom.xml.Attribute;
import org.mybatis.generator.api.dom.xml.TextElement;
import org.mybatis.generator.api.dom.xml.XmlElement;
import org.mybatis.generator.codegen.mybatis3.MyBatis3FormattingUtilities;
import org.mybatis.generator.codegen.mybatis3.xmlmapper.elements.AbstractXmlElementGenerator;

/**
 * User: landy
 * Date: 14-6-23
 * Time: 上午9:22
 */
public class CountBySelectiveElementGenerator extends
        AbstractXmlElementGenerator {
    @Override
    public void addElements(XmlElement parentElement) {
        XmlElement answer = new XmlElement("select"); //$NON-NLS-1$

        answer.addAttribute(new Attribute(
                "id", ((IntrospectedTableMyBatis3Freework) introspectedTable).getCountBySelectiveStatementId())); //$NON-NLS-1$
        answer.addAttribute(new Attribute("resultType", "java.lang.Integer")); //$NON-NLS-1$ //$NON-NLS-2$

        String parameterType;
        if (introspectedTable.getRules().generateBaseRecordClass()) {
            parameterType = introspectedTable.getBaseRecordType();
        } else {
            parameterType=introspectedTable.getPrimaryKeyType();
        }

        answer.addAttribute(new Attribute("parameterType", //$NON-NLS-1$
                parameterType));

        context.getCommentGenerator().addComment(answer);

        StringBuilder sb = new StringBuilder();
        sb.append("select count(*) from "); //$NON-NLS-1$
        sb.append(introspectedTable
                .getAliasedFullyQualifiedTableNameAtRuntime());
        answer.addElement(new TextElement(sb.toString()));

        XmlElement where = new XmlElement("where");
        boolean and=false;
        for(IntrospectedColumn introspectedColumn : introspectedTable.getNonPrimaryKeyColumns()) {
            XmlElement ifEle = new XmlElement("if");
            ifEle.addAttribute(new Attribute("test",introspectedColumn.getJavaProperty()+" != null"));
            sb.setLength(0);
            if(and){
                sb.append(" and ");
            }else{
                and=true;
            }
            sb.append(MyBatis3FormattingUtilities.getAliasedEscapedColumnName(introspectedColumn));
            sb.append(" = ");
            sb.append(MyBatis3FormattingUtilities.getParameterClause(introspectedColumn));
            ifEle.addElement(new TextElement(sb.toString()));

            where.addElement(ifEle);
        }
        answer.addElement(where);

        parentElement.addElement(answer);
    }
}
